import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Modal, Select, Tooltip, Upload } from 'antd';
import { FormInstance } from 'antd/lib/form/hooks/useForm';
import React from 'react';
import { AddBatchTaskBean } from '../data';
import { exportBatchTask } from '../service';
import { getTenantList } from '@/pages/Tenant/Tenant/service';

interface AddFormProps {
  onSubmit: (values: AddBatchTaskBean) => void;
  onCancel: (flag?: boolean) => void;
  modalVisible: boolean;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 4 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 20 },
    sm: { span: 20 },
  },
};

function downloadImportFile(form: FormInstance<any>) {
  const batchType = form.getFieldValue('task_type');
  if (!batchType) {
    message.error('请先选择任务类型,然后下载对应的模板文件');
    return;
  }

  if (batchType === '1') {
    exportBatchTask({ type: 1 }).then(res => {
      const link = document.createElement('a')
      let blob = new Blob([res], { type: 'application/octer-stream' });
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob);
      link.setAttribute('download', `路段导入模板.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    })
  } else if (batchType === '3') {
    exportBatchTask({ type: 3 }).then(res => {
      const link = document.createElement('a')
      let blob = new Blob([res], { type: 'application/octer-stream' });
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob);
      link.setAttribute('download', `设备导入模板.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    })
  } else {
    message.error('任务类型错误,没有模板下载');
  }
  return undefined;
}

const batchTypes = [
  { label: '路段导入', value: '1' },
  { label: '设备导入', value: '3' },
];

let tenantList: any[] = [];

getTenantList({}).then((res) => {
  tenantList = res.data?.map((item: { id: any; name: any }, _index: any) => {
    return {
      value: item.id,
      label: item.name,
    };
  });
})

const AddForm: React.FC<AddFormProps> = (props) => {
  const [form] = Form.useForm();

  const {
    onSubmit: handleAdd,
    onCancel: handleAddModalVisible,
    modalVisible: addModalVisible,
  } = props;

  const onModalOk = async () => {
    const fieldsValue = (await form.validateFields()) as AddBatchTaskBean;
    console.log(fieldsValue);
    
    handleAdd(fieldsValue);
  };

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  return (
    <Modal
      title="新建批量导入任务"
      open={addModalVisible}
      destroyOnClose
      width={800}
      onOk={() => onModalOk()}
      onCancel={() => handleAddModalVisible(false)}
      afterClose={() => handleAddModalVisible()}
      okText="确定"
      cancelText="取消"
    >
      <Form {...formItemLayout} form={form} layout={'vertical'}>

        <Form.Item name="tenant_id" label="所属用户">
          <Select
            options={tenantList}
            onChange={(value) => {
              form.setFieldsValue({ tenant_id: value });
            }}
          />
        </Form.Item>

        <Form.Item name="name" label="任务名称" rules={[{ required: true, message: '必填' }]}>
          <Input />
        </Form.Item>

        <Form.Item name="task_type" label="任务类型" rules={[{ required: true, message: '必填' }]}>
          <Select
            options={batchTypes}
            style={{ width: 120 }}
            onChange={(value) => {
              form.setFieldsValue({ task_type: value });
              console.log(form);
            }}
          />
          <Tooltip title="模板下载">
            <Button icon={<DownloadOutlined />} onClick={() => downloadImportFile(form)}>
              模板下载
            </Button>
          </Tooltip>
        </Form.Item>

        <Form.Item
          name="batch_file_url"
          label="文件"
          valuePropName="fileList"
          getValueFromEvent={normFile}
          extra="选择导入数据文件"
        >
          <Input.Group compact>
            <Upload
              name="file"
              action="/api/minio/file/uploadFile"
              onChange={(info) => {
                form.setFieldsValue({ batch_file_url: info.file.response?.data?.url });
                console.log(form.getFieldValue('batch_file_url'));
              }}
            >
              <Button icon={<UploadOutlined />}>选择导入数据文件</Button>
            </Upload>
          </Input.Group>

        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddForm;
